<?php
/*
Plugin Name: HyperBoard
Plugin URI: http://hyperboard.codeplex.com
Description: Web development tool, agile whiteboard with sticky notes. Your notes are posts in WP!
Version: 0.6
Author: Hypernode AB, Andreas Ek
Author URI: http://www.hypernode.se
License: MIT
*/
add_filter('the_content', 'HyperBoard');
add_action('wp_print_styles', 'add_hyperboard_stylesheet');
add_action('init', 'hyperboard_init_method');
add_action('wp_ajax_hyperboard_insert_note', 'ajax_insert_note');
add_action('wp_ajax_nopriv_hyperboard_insert_note', 'ajax_insert_note');
add_action('wp_ajax_hyperboard_update_position', 'ajax_update_position');
add_action('wp_ajax_nopriv_hyperboard_update_position', 'ajax_update_position');
add_action('wp_ajax_nopriv_hyperboard_delete_note', 'ajax_delete_note');
/* getNotes generates a string with inline html notes from wpdb table */
function getNotes() {

	global $post; // required
	$args = array('meta_key' => 'hyperboard', 'meta_value' => get_the_ID());
	
	
	$custom_posts = get_posts($args);
	foreach($custom_posts as $post) : setup_postdata($post);

		$dataString = get_post_meta($post->ID,'hyperboard-data');
		$dataArr = json_decode($dataString[0]);
		if ($dataArr!=NULL)
		{
			list($left,$top,$zindex) = explode('x', $dataArr->xyz);
			$notes.= '<div id="hyperboard_note_'.$post->ID.'" class="note '.$dataArr->color.'" style="left:'.$left.'px;top:'.$top.'px;z-index:'.$zindex.'">
<div class="body">'.$post->post_title.'</div>
<div class="author">'.htmlspecialchars($dataArr->author).'</div>
<span class="data hidden_field">'.$dataArr->id.'</span>
<span class="color hidden_field">'.$dataArr->color.'</span>
<div class="time">
<span class="timeleft">'.$dataArr->timeleft.'</span>/<span class="estimate">'.$dataArr->estimate.'</span>
</div>
</div>';
		}

	endforeach;
	wp_reset_postdata();

	return $notes;
}
/* noteDialog generates a string with inline html for template input form */
function noteDialog() {
    $str = '<div id="previewNote" class="note yellow">
        <div class="body"></div>
        <div class="author"></div>
        <span class="data hidden_field">0</span>
        <span class="color hidden_field">yellow</span>
        <div class="time">
        <span class="timeleft">0</span>/<span class="estimate">0</span>
        </div>
    </div>
    <div id="noteData"> <!-- Holds the form -->
    <form action="" method="post" class="note-form">
    <label for="note-body">Text of the note</label>
    <textarea name="note-body" id="note-body" class="pr-body" cols="30" rows="6"></textarea>
    <label for="note-estimate">Estimate</label>
    <input type="text" name="note-estimate" id="note-estimate" class="pr-estimate numbersOnly" value="0" />
    <label for="note-name">Time left</label>
    <input type="text" name="note-timeleft" id="note-timeleft" class="pr-timeleft numbersOnly" value="0" />
    <label for="note-name">Your name</label>
    <input type="text" name="note-name" id="note-name" class="pr-author" value="" />
    <label>Color</label> <!-- Clicking one of the divs changes the color of the preview -->
    <div class="color yellow"></div>
    <div class="color blue"></div>
    <div class="color green"></div>
    <div class="color purple"></div>
    <div class="color orange"></div>
    <div class="color pink"></div>
    <span class="board hidden_field">'.get_the_ID().'</span>
    <div class="clear"></div>
    <button id="note-submit" class="dialog_button">Submit</button>
    <button id="note-post" class="dialog_button">To Post</button>
    <button id="note-close">Cancel</button>
    </form>
    </div>';
    return $str;
}
/* The general start function that replaces inline content with the plugin */
function HyperBoard($text) {
	$board = '<div id="hyperboardmain"><button class="add_new_note yellow">Add a note</button>' . getNotes() . '</div><div style="display:none">
	<div id="noteDialog" class="ui-dialog" title="Edit your note">' . noteDialog() . '</div></div>' . footerNotis();
	$text = str_replace('[HyperBoard]', $board, $text);
	return $text;
}
/*Required stylesheets */
function add_hyperboard_stylesheet() {
	$myStyleUrl = WP_PLUGIN_URL . '/hyperboard/styles.css';
	$myStyleFile = WP_PLUGIN_DIR . '/hyperboard/styles.css';

        if ( file_exists($myStyleFile) ) {
            wp_register_style('HyperBoardStyleSheets', $myStyleUrl);
            wp_enqueue_style( 'HyperBoardStyleSheets');
        }
}
function hyperboard_init_method() {
    if (!is_admin()) {

    	wp_enqueue_script('jquery');
    	/*wp_enqueue_script('jquery-ui-core');*/
    	
    	wp_enqueue_script('jquery-ui-draggable');
    	wp_enqueue_script('jquery-ui-dialog');

        $myScriptUrl = WP_PLUGIN_URL . '/hyperboard/script.js';
        wp_deregister_script( 'hyperboardjs' );
        wp_register_script( 'hyperboardjs', $myScriptUrl);
        wp_enqueue_script( 'hyperboardjs' );
    }
}

function ajax_insert_note()
{
	// Error reporting
	error_reporting(E_ALL^E_NOTICE);
	// Checking whether all input variables are in place:
	if(!is_numeric($_POST['zindex']) || !isset($_POST['author']) || !isset($_POST['body']) || !in_array($_POST['color'],array('yellow','green','blue','purple','orange','pink')))
    {
        die("0");
    }
	if(ini_get('magic_quotes_gpc'))
	{
		// If magic_quotes setting is on, strip the leading slashes that are automatically added to the string:
		$_POST['author']=stripslashes($_POST['author']);
		$_POST['body']=stripslashes($_POST['body']);
	}
	// Escaping the input data:
	$author = mysql_real_escape_string(strip_tags($_POST['author']));
	$body = mysql_real_escape_string(strip_tags($_POST['body']));
    $color = mysql_real_escape_string($_POST['color']);
    $id = mysql_real_escape_string($_POST['id']);
    $pos = mysql_real_escape_string($_POST['pos']);
	$zindex = (int)$_POST['zindex'];
    $board = (int)$_POST['board'];
    $estimate = (int)$_POST['estimate'];
    $timeleft = (int)$_POST['timeleft'];

	$dataArr = array('id'=>0,'author'=>$author,'color'=>$color,'zindex'=>$zindex,'estimate'=>$estimate,'timeleft'=>$timeleft,'xyz'=>$pos);

    if (is_numeric($id) && $id>0)
    {

    	global $user_ID;
		$old_post = array(
			'post_id' => $id,
			'post_title' => $body,
			'post_status' => 'publish',
			'post_date' => date('Y-m-d H:i:s'),
			'post_author' => $user_ID,
			);
		wp_update_post($old_post);
		
		$dataString = get_post_meta($id,'hyperboard-data');
		$dataArrOld = json_decode($dataString[0]);
		
		$dataArr['xyz'] = $dataArrOld->xyz;
		$dataArr['id'] = $id;
		if (!update_post_meta($id, 'hyperboard-data', json_encode($dataArr)))
		{
			add_post_meta($id, 'hyperboard-data', json_encode($dataArr),true);
		}

        echo '<post>'.$id.'</post>';
    }
    else
    {

    	global $user_ID;
		$new_post = array(
			'post_title' => $body,
			'post_content' => '',
			'post_status' => 'publish',
			'post_date' => date('Y-m-d H:i:s'),
			'post_author' => $user_ID,
			'post_type' => 'post',
			'post_category' => array(0)
			);
		$post_id = wp_insert_post($new_post);

		add_post_meta($post_id, 'hyperboard', ''.$board, true);
		
		$dataArr['id'] = $post_id;
		$dataArr['xyz'] = '42x72x'.$zindex;
		add_post_meta($post_id, 'hyperboard-data', json_encode($dataArr), true);

        echo '<post>'.$post_id-'</post>';
    }
}

function ajax_update_position()
{
    // Error reporting
    error_reporting(E_ALL^E_NOTICE);
    // Validating the input data:
    if(!is_numeric($_GET['id']) || !is_numeric($_GET['x']) || !is_numeric($_GET['y']))
    {
    	die("0");
    }
    
    
    // Escaping:
    $id = (int)$_GET['id'];
    $x = (int)$_GET['x'];
    $y = (int)$_GET['y'];
   	$z = 0;
    if(is_numeric($_GET['z']))
    {
    	$z = (int)$_GET['z'];
    }
    $pos = $x.'x'.$y.'x'.$z;
    // Saving the position and z-index of the note:

	$dataString = get_post_meta($id,'hyperboard-data');
	
	$dataArr = json_decode($dataString[0]);

	$dataArr->xyz = $pos;

	if (!update_post_meta($id, 'hyperboard-data', json_encode($dataArr)))
	{
		add_post_meta($id, 'hyperboard-data', json_encode($dataArr),true);
	}
	
    echo "1";
}
/* a string with inline footer for the reference to codeplex project */
function footerNotis()
{
    $str = '<a href="http://hyperboard.codeplex.com">HyperBoard @ Codeplex</a>';
    return $str;
}
?>